/*
 * Copyright (c) 2024-2025.  little3201.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.leafage.exploiter.service.impl;

import io.leafage.exploiter.service.DBService;
import io.leafage.exploiter.vo.ColumnVO;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Types;
import java.util.List;

/**
 * db service for postgres
 *
 * @author wq li
 */
@Service
public class DBServiceImpl implements DBService {

    @Override
    public List<String> findAllTables(String host, Integer port, String name, String username, String password) {
        DataSource dataSource = createDataSource(host, port, name, username, password);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

        String sql = "SELECT table_name as tableName " +
                "FROM information_schema.TABLES " +
                "WHERE table_schema = 'public'";
        return jdbcTemplate.queryForList(sql, String.class);
    }

    @Override
    public List<ColumnVO> findAllColumnsByTableName(String host, Integer port, String name, String username, String password, String tableName) {
        DataSource dataSource = createDataSource(host, port, name, username, password);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        String sql = "SELECT " +
                "column_name as columnName, " +
                "udt_name as dataType, " +
                "case is_nullable when 'YES' then true else false end as nullable, " +
                "character_maximum_length as maximumLength " +
                "FROM information_schema.COLUMNS " +
                "WHERE table_name = ? ";
        return jdbcTemplate.query(sql, new Object[]{tableName}, new int[]{Types.VARCHAR}, new BeanPropertyRowMapper<>(ColumnVO.class));
    }

    private DataSource createDataSource(String host, int port, String name, String username, String password) {
        String url = "jdbc:postgresql://" + host + ":" + port + "/" + name;
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName("org.postgresql.Driver");
        return dataSource;
    }
}
